<template>
  <a-modal
    v-model:open="visible"
    title="编辑个人资料"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="500px"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item label="用户名" name="userName">
        <a-input
          v-model:value="formData.userName"
          placeholder="请输入用户名"
          :maxlength="50"
        />
      </a-form-item>

      <a-form-item label="头像" name="userAvatar">
        <a-input
          v-model:value="formData.userAvatar"
          placeholder="请输入头像URL"
        />
        <div v-if="formData.userAvatar" class="avatar-preview">
          <a-avatar :src="formData.userAvatar" :size="64" />
        </div>
      </a-form-item>

      <a-form-item label="个人简介" name="userProfile">
        <a-textarea
          v-model:value="formData.userProfile"
          placeholder="请输入个人简介"
          :rows="4"
          :maxlength="200"
          show-count
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { updateUserInfo } from '@/api/userController'
import { useLoginUserStore } from '@/stores/loginUser'

interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const loginUserStore = useLoginUserStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

const visible = ref(false)

// 表单数据
const formData = reactive({
  userName: '',
  userAvatar: '',
  userProfile: ''
})

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 50, message: '用户名长度在1-50个字符', trigger: 'blur' }
  ]
}

// 监听props变化
watch(
  () => props.open,
  (newVal) => {
    visible.value = newVal
    if (newVal) {
      // 打开模态框时，初始化表单数据
      const loginUser = loginUserStore.loginUser
      formData.userName = loginUser.userName || ''
      formData.userAvatar = loginUser.userAvatar || ''
      formData.userProfile = loginUser.userProfile || ''
    }
  },
  { immediate: true }
)

// 监听visible变化
watch(visible, (newVal) => {
  emit('update:open', newVal)
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const updateData: API.UserUpdateRequest = {
      id: loginUserStore.loginUser.id,
      userName: formData.userName,
      userAvatar: formData.userAvatar,
      userProfile: formData.userProfile
    }

    const res = await updateUserInfo(updateData)

    if (res.data.code === 0) {
      message.success('个人资料更新成功')

      // 更新本地用户信息
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        userName: formData.userName,
        userAvatar: formData.userAvatar,
        userProfile: formData.userProfile
      })

      visible.value = false
      emit('success')
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  visible.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped>
.avatar-preview {
  margin-top: 8px;
}
</style>
